# hive_app/forms.py
from django import forms
from django.contrib.auth.hashers import make_password
from .models import User


class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput, required=False)

    class Meta:
        model = User
        fields = ['username', 'password', 'user_type', 'createTime']
        widgets = {
            'createTime': forms.DateInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 编辑时密码字段可选
        if self.instance.pk:
            self.fields['password'].required = False
            self.fields['password'].help_text = "留空则不修改密码"

    def save(self, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data.get('password')
        if password:
            user.password = password
        if commit:
            user.save()
        return user